/*
* Copyright (c) 2016 . All Rights Reserved.
*/
package com.cgmnx.admin.service.sys.impl;

import com.cgmnx.admin.common.exception.ServiceException;
import com.cgmnx.admin.common.util.FileUtil;
import com.cgmnx.admin.service.sys.FileUploadService;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

/**
 * @author: created  Date: 16/12/20 Time: 下午2:29
 * @version: 1.0
 */
@Slf4j
@Service("localFileUploadService")
public class LocalFileUploadServiceImpl implements FileUploadService {

    private static final Set<String> IMAGE_SUFFIX = Sets.newHashSet("png", "jpg", "gif", "jpeg");

    @Value("${file.store.path}")
    public String path;

    @Override
    public String upload(String key, byte[] bytes) {
        throw new UnsupportedOperationException();

    }

    @Override
    public String upload(String originalFileName, InputStream inputStream) {

        if (StringUtils.isBlank(originalFileName) || inputStream == null) {
            return StringUtils.EMPTY;
        }

        if (StringUtils.isBlank(path)) {
            path = FileUtil.getStore();
        }

        String filePath = path + originalFileName;

        try {

            FileUtils.copyInputStreamToFile(inputStream, new File(filePath));

        } catch (IOException e) {
            log.error("保存文件错误,文件路径:{}", filePath);
            throw new ServiceException("保存文件错误");
        }

        return filePath;
    }


    @Override
    public InputStream download(String location) {

        if (StringUtils.isBlank(location)) {
            return null;
        }

        File file = new File(location);
        if(!file.exists()) {
            return null;
        }
        try {
            return FileUtils.openInputStream(file);
        } catch (IOException e) {
            log.error("创建文件的输入流错误,文件路径:{}", file);
            throw new ServiceException("创建文件的输入流错误");
        }

    }

}